/*本模块功能:详情页(学生)
        编写者:朱光曜
        编写时间:2017.11.03*/
$(function() {
    var string1 = '';
    var box1 = new Confirm;
    var box = new Alert;
    var box2 = new Alert;
    var bool = true;

    function formatDate(now) {//处理时间戳
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hour = now.getHours();
        var minute = now.getMinutes();
        if(month<10){month="0"+month;}
        if(date<10){date="0"+date;}
        if(hour<10){hour="0"+hour;}
        if(minute<10){minute="0"+minute;}
        return year + "-" + month + "-" + date + "   " + hour + ":" + minute;
    }

    function alertContent(questionContent) { //问题

        return '<div class="fl headPort" problemId="' + questionContent.problemMap.problemId + '"><p class="fl headPortrait"><img src="' + questionContent.imageUrl+questionContent.problemMap.headIcon+ '"/></p></div>' +
            '<div class="fl message">' +
            '<div>'+
            '<span class="fl identity myQuestionName">'+ questionContent.problemMap.userName +'</span><span class="fl time myQuestionTime">'+ timeObject.changedateTime(questionContent.problemMap.problenTime) +'</span>'+
            '</div>'+
            '<div>' +
            '<span class="fl">问题标题:&ensp;</span><span class="fl">' + unescape(questionContent.problemMap.problemName) + '</span>' +
            '</div>' +
            '<div class="clear"></div>' +
            '<div class="message_content">' +
            '<span class="fl">问题描述:&ensp;</span><span  class="fl">' + unescape(questionContent.problemMap.problemContent) + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="clear"></div>';

    }

    function tabelModel(data) { //回答
        var time = new Date(data.answerList[key].answerTime);
        var str = "";
        if(data.answerList[key].isMark == 1) {
            str = '<span class="fr">学生</span>';
        }
        if(data.answerList[key].roleId == 2) {
            str = '<span class="fr">教师</span>';
        }
        return '<div class="funBox answer_list" answerId="' + data.answerList[key].answerId + '">' +
            '<div class="fl headPort">' +
            '<p class="fl headPortrait"><img src="' + data.imageUrl+data.answerList[key].headIcon + '" /></p>' +
            '</div>' +
            '<div class="fl message">' +
            '<div>' +
            '<span class="fl identity">' + data.answerList[key].userName + '&ensp;' + str + '</span><span class="fl time">' + formatDate(time) + '</span>' +
            '</div>' +
            '<div class="clear"></div>' +
            '<div class="answer_list_answer">' +
            '<span style="font-weight: bolder;">回答:&ensp;&ensp;</span><span  class="answer_list_answer_area"><div  class="copy"> ' +unescape(data.answerList[key].answerContent) + '<div class="clear"></div></div></span><i class="last">展开</i><div class="clear"></div>' +
            '</div>' +
            '</div>' +
            '<div class="publicBtn deleteAnswer fr">删除回答</div>' +
            '<div class="clear"></div>' +
            '</div>';

    }
    var loading1 = new Loading();//监控全局ajax添加loading
    loading1.init();
    $(document).ajaxSend(function(){
        loading1.show();

    });
    $(document).ajaxStop(function(){
        loading1.hide();

    });
    var nowData = 1;
    var index = {
        init: function() {
            this.bind();
        },
        bind: function() {
            var self = this;
            this.data_content = {}; //搜索集
            this.tab_content = {}; //列表集
            this.parameter = {
                "pageNow": 1,
                "pageSize": 10,
                "isMark":result.paramData.isMark,
                "problemId":result.paramData.problemId
            };

            this.postData(this.parameter, nowData);
            if(result.paramData.isMark==0){
                $(".returnBox .looktg").attr("data-url","studentAnswer");
            }else if(result.paramData.isMark==1){
                $(".returnBox .looktg").attr("data-url","studentMyQuestion");
            }else if(result.paramData.isMark==2){
                $(".returnBox .looktg").attr("data-url","studentMyAnswer");
            }



            /*$(".answer_list_answer .answer_list_answer_area span").on('change', function(e) {
                alert($(this).parents(".answer_list").html())
                $(this).parents(".answer_list").css("height", 114 + parseInt($(this).height()) + "px");

            })*/
            $(".deleteQuestion").click(function() {//删除提问事件
                var arr=[];
                var problemId = $(".putQuestions .headPort").attr("problemId");
                arr.push(problemId);
                var conParameter = {
                    "list": arr
                };
                self.alert3("确定删除这条提问么", conParameter, "delProblem");

            });

            $(document).on("click",".deleteAnswer",function() {//删除答案事件
                var arr=[];
                var answerId = $(this).parents(".answer_list").attr("answerId");
                arr.push(answerId);
                var conParameter = {
                    "list": arr
                };
                self.alert3("确定删除这条回答么", conParameter, "delAnswer");
            });

        },
        postData: function(par_data, nowData, hunt) { //获得搜索及列表数据
            var self = this;
            var parameter = par_data;

            $.ajax({
                type: "post",
                url: "getProblemDetail",
                async: true,
                data: {
                    "jsonStr": JSON.stringify(parameter)
                },
                success: function(data, status, xhr) {
                    var new_data = JSON.parse(data);
                    if(new_data.result == "success"){
                        if(new_data.excuseMark == 1){
                            $(".myAnswer").css({"background":"#ccc","cursor":"default","margin": "20px 0 0 137px"});
                            $(".myAnswer").removeClass("myAnswer");
                            $(".myAnswer").off("click");
                        }
                        /*var i = 0;
                       for(key in parameter) {
                           i++
                       }
                       if(i > 3) {
                           self.tab_content = new_data;

                           self.tab_add();
                       } else {*/

                        self.data_content = new_data;
                        self.tab_content = new_data;

                        self.add();
                        self.tab_add();
                        /*}*/

                        if(result.paramData.isMark == 1) {
                            $(".deleteAnswer").remove();
                        } else if(result.paramData.isMark == 2) {

                            $(".deleteQuestion").remove();
                        } else {
                            $(".deleteQuestion").remove();
                            $(".deleteAnswer").remove();
                        }
                        // console.log(new_data.totalPage+"啊啊"+new_data.pageNow)
                        var sumpage = new_data.totalPage;
                        if(sumpage<1){sumpage=1;};

                        var nowpage = 1;
                        var pagenumber = 10;
                        var parame = parameter;
                        $(".tcdPageCode").createPage({
                            pageCount: sumpage, //总页数
                            current: nowpage, //当前页数
                            pageNumber: pagenumber, //每页显示数量
                            backFn: function(p) {

                                nowpage = p;

                                if(nowpage >= sumpage) {
                                    nowpage = sumpage;
                                }
                                if(!parameter) {
                                    parameter = {
                                        "pageNow": nowpage,
                                        "pageSize": 10
                                    };

                                } else {
                                    parameter.pageNow = nowpage;

                                }
                                $.ajax({
                                    type: "post",
                                    url: "getProblemDetail",
                                    async: true,
                                    data: {
                                        "jsonStr": JSON.stringify(parameter)
                                    },
                                    async: true,
                                    success: function(msg) {
                                        //获取院系
                                        var msgNew = JSON.parse(msg);
                                        if(msgNew.excuseMark == 1){
                                            $(".myAnswer").css({"background":"#ccc","cursor":"default","margin": "20px 0 0 137px"});
                                            $(".myAnswer").removeClass("myAnswer");
                                            $(".myAnswer").off("click");
                                        }
                                        self.tab_content = msgNew;

                                        self.tab_add();
                                        if(result.paramData.isMark == 1) {
                                            $(".deleteAnswer").remove();
                                        } else if(result.paramData.isMark == 2) {

                                            $(".deleteQuestion").remove();
                                        } else {
                                            $(".deleteQuestion").remove();
                                            $(".deleteAnswer").remove();
                                        }
                                    },
                                    error: function(data, status, xhr) {
                                        var json = JSON.stringify({
                                            "pageName": "error"
                                        });
                                        window.location.href = "skipPage?jsonStr=" + json;

                                    }
                                });
                            }
                        });
                    }else{
                        if(new_data.failMsg == "暂无权限"){
                            parent.location.reload(true);
                        }
                    }

                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });
        },
        add: function() { //搜索追加
            var self = this;
            var data = self.data_content;
            $(".mainContent .putQuestions").html(alertContent(data));

            $(".mainContent .myAnswer").click(function() { //我要提问点击
                var $_self = self;
                self.alert2('<div id="odiv" style="display:none;position:absolute;z-index:100;"></div><div onmousedown="show_element(event)" style="clear:both" id="customized-buttonpane" class="editor"></div>');
                $("#customized-buttonpane").trumbowyg({ //编辑器插件启动
                    lang: 'zh_cn',
                    closable: false,
                    fixedBtnPane: false,
                    btnsDef: {
                        // Customizables dropdowns
                        align: {
                            dropdown: ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull'],
                            ico: 'justifyLeft'
                        },
                        image: {
                            dropdown: ['insertImage', 'base64'],
                            ico: 'insertImage'
                        }
                    },
                    btns: ['viewHTML',
                        '|', 'formatting',
                        '|', 'btnGrp-test',
                        '|', 'align',
                        '|', 'btnGrp-lists',
                        '|', 'image'
                    ]
                });

                $(".trumbowyg-box").removeAttr("title");
                $(".image-trumbowyg-dropdown").removeAttr("title");

            });

        },
        tab_add: function() { //列表追加

            var self = this;
            var data = self.tab_content;
            var table = string1;

            //data.selectList={};

            var i = 0;
            for(key in data.answerList) {//检查是否数据为0
                i++;

            }

            if(i > 0) {

                for(key in data.answerList) {

                    table += tabelModel(data);
                }

                $(".answer_content_list .answer_content_list_area").html(table);
            } else {
                $(".answer_content_list").css("display","none");
            }
            $(".answer_list_answer .answer_list_answer_area .copy img").each(function(){//遍历高度添加属性
                var thisHeight=this.offsetHeight;
                $(this).attr("height",thisHeight);
            });
            $(document).ready(function(){
                var maxHeight = 80;
                $(".answer_list_answer .answer_list_answer_area .copy").each(function() {//超出文字显示下拉事件

                    var thisHeight=this.offsetHeight;

                    $(this).attr("height",thisHeight);
                    if(thisHeight > maxHeight) {

                        bool=true;
                        $(this).parents(".answer_list_answer_area").css({"height":maxHeight+"px","overflow":"hidden"});

                        $(this).parent("span").siblings("i").css({"display":"block"});
                    }
                });

                $(".answer_list_answer").find(".last").on("click", function() {//超出文字显示下拉点击事件
                    var self = $(this);
                    if(bool) {
                        self.parents(".answer_list").animate({"height":parseInt($(this).siblings(".answer_list_answer_area").children(".copy").attr("height"))+175-maxHeight+"px"},300);
                        $(this).siblings(".answer_list_answer_area").animate({"height":$(this).siblings(".answer_list_answer_area").children(".copy").attr("height")+"px"},300);
                        $(this).html("关闭");

                        bool = false;
                    } else {


                        self.parents(".answer_list").animate({"height":175+"px"},300);
                        $(this).siblings(".answer_list_answer_area").animate({"height":maxHeight+"px"},300);
                        $(this).html("展开");
                        bool = true;
                    }

                });
            });
        },
        alert1: function(content1,state) { //alert提示

            box2.contenthead = "提示";
            box2.content = content1;

            box2.success = function() {
                if(result.paramData.isMark==1&&state=="del"){
                    var json=JSON.stringify({
                        "pageName":"studentMyQuestion",
                        "paramData":{

                        }
                    });
                    //console.log($(this).parents("tr").html());
                    window.location.href="skipPage?jsonStr="+json;
                }else{
                    box2.hide();
                    window.location.reload();
                }

            };

            box2.init();
            box2.show();
        },
        alert2: function(content2, method) { //弹出层事件
            var self = this;
            box.contenthead = "我要回答";
            box.content = content2;

            box.success = function() {//提交
                $(".alert").removeAttr("id");
                var customized_buttonpane = $("#customized-buttonpane").html();
                var answerContent = escape(customized_buttonpane);
                var stuorteaId = $('#questionUp .publicSelect  option:selected').attr("courseId");

                if(customized_buttonpane == "") {

                    self.alert1("请输入内容");
                    return;
                }

                var methodConParameter = {
                    "answerContent": answerContent,
                    "problemId": result.paramData.problemId,
                    "stuorteaId": stuorteaId,
                    "courseId":self.data_content.problemMap.courseId
                };

                $.ajax({
                    type: "post",
                    url: "answerProblem",
                    async: true,

                    data: {
                        "jsonStr": JSON.stringify(methodConParameter)
                    },
                    success: function(msg) {

                        var msgNew = JSON.parse(msg);

                        if(msgNew.result == "success") {
                            self.alert1("提交成功");
                        } else {
                            //self.alert1("提交失败");
                            if(msgNew.errorMsg){
                                self.alert1(msgNew.errorMsg);
                            }else{
                                self.alert1("提交失败");
                            }

                        }

                    },
                    error: function(data, status, xhr) {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;

                    }
                });

            };

            box.init();
            $(".alert").attr("id", "studentAnswer");

            $(".alert_btn .alert_confirm").html("提交");

            box.show();
            $("#studentAnswer .alert_img").hover(function() { //禁止点叉提交
                box.success = function() {
                    $(".alert").removeAttr("id");
                    box.hide();
                };
            }, function() {

                box.success = function() {//提交
                    $(".alert").removeAttr("id");
                    var customized_buttonpane = $("#customized-buttonpane").html();
                    var answerContent = escape(customized_buttonpane);
                    var stuorteaId = $('#questionUp .publicSelect  option:selected').attr("courseId");

                    if(customized_buttonpane.replace(/[ ]|[&nbsp;]/g, '') == "") {

                        self.alert1("请输入内容");
                        return;
                    }

                    var methodConParameter = {
                        "answerContent": answerContent,
                        "problemId": result.paramData.problemId,
                        "stuorteaId": stuorteaId
                    };

                    $.ajax({
                        type: "post",
                        url: "answerProblem",
                        async: true,

                        data: {
                            "jsonStr": JSON.stringify(methodConParameter)
                        },
                        success: function(msg) {

                            var msgNew = JSON.parse(msg);

                            if(msgNew.result == "success") {
                                self.alert1("提交成功");
                            } else {
                                //self.alert1("提交失败");
                                if(msgNew.errorMsg){
                                    self.alert1(msgNew.errorMsg);
                                }else{
                                    self.alert1("提交失败");
                                }

                            }

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });

                }
            });
            var backups =box.success;
            $("#customized-buttonpane").css({
                "overflow-y": "scroll",
                "height": "276px"
            });
            $("#customized-buttonpane").keydown(function(event) { //禁用回车跳页
                //backups = box.success;
                var keycode = event.which;

                if(keycode == 13) {
                    box.success = function() {};
                    box.hide = function() {};
                }

            });
            $("#customized-buttonpane").keyup(function() { //禁用回车跳页
                box.success =backups;

                box.hide = function() {
                    box.panel.style.display = "none";
                    box.abs_bg.style.display = "none";
                };

            });
        },
        alert3: function(content3, methodConParameter1, urls) { //删除按钮事件
            box1.contenthead = "提示";
            box1.content = content3;
            var self = this;

            box1.success = function() {
                $.ajax({
                    type: "post",
                    url: urls,
                    async: true,

                    data: {
                        "jsonStr": JSON.stringify(methodConParameter1)
                    },
                    success: function(msg) {

                        var msgNew = JSON.parse(msg);

                        if(msgNew.result == "success") {
                            self.alert1("删除成功","del");


                        } else {
                            //self.alert1("删除失败");
                            if(msgNew.errorMsg){
                                self.alert1(msgNew.errorMsg);
                            }else{
                                self.alert1("删除失败");
                            }

                        }

                    },
                    error: function(data, status, xhr) {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;

                    }
                });

            };

            box1.init();
            box1.show();
        }

    };
    index.init();

});